<template>
  <jy-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
    <div class="print-box" v-loading="printLoading">
      <canvas class="qrcode" ref="qrcodeCanvas"></canvas>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" :disabled="printLoading" @click="doPrinter">打 印</el-button>
      <el-button size="small" @click="cancel">关 闭</el-button>
    </div>
  </jy-dialog>
</template>
<script>
import QRCode from "qrcode";
import html2canvas from "html2canvas";
export default {
  name: "QrcodeView",
  data() {
    return {
      loading: false,
      // 弹出层标题
      title: "试验报告二维码",
      // 是否显示弹出层
      open: false,
      isPdf: false,
      printLoading: false
    };
  },
  created() {},
  mounted() {},
  methods: {
    init(str) {
      if (!str) {
        return;
      }
      this.open = true;
      this.$nextTick(() => {
        this.generateQRCode(str);
      });
    },
    generateQRCode(text) {
      QRCode.toCanvas(this.$refs.qrcodeCanvas, text, function (error) {
        if (error) console.error(error);
        // console.log("QR Code generated!");
      });
    },
    // 生成图片
    async doPrinter() {
      this.printLoading = true;
      let reportItem = document.querySelector(".print-box");
      let div = document.createElement("div");
      const canvas = await html2canvas(reportItem, {
        scale: 2,
        backgroundColor: "#ffffff",
        useCORS: true,
        scrollY: 0,
        scrollX: 0
      });
      const imgData = canvas.toDataURL("image/jpeg", 1.0);
      let img = document.createElement("img");
      img.classList.add("printCodeImg");
      img.src = imgData;
      div.appendChild(img);
      console.log(div);
      this.$print(div);
      this.printLoading = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
    }
  }
};
</script>
<style lang="scss" scoped>
  .qrcode {
    display: block;
    margin: 0 auto 20px auto;
    width: 200px !important;
    height: 200px !important;
  }
</style>
